// admin/system/dao/sys_oper_log_dao.go
package dao

import (
	"go-admin1/admin/system/model"
	"go-admin1/internal/infrastructure/database"
	"go-admin1/internal/infrastructure/logger"

	"go.uber.org/zap"
	"gorm.io/gorm"
)

// SysOperLogDao 操作日志数据访问接口
type SysOperLogDao interface {
	Create(operLog *model.SysOperLog) error
	GetByID(id int64) (*model.SysOperLog, error)
	Delete(id int64) error
	List(page, pageSize int) ([]*model.SysOperLog, int64, error)
	CleanAll() error
}

type sysOperLogDao struct {
	db *gorm.DB
}

// NewSysOperLogDao 创建操作日志数据访问实例
func NewSysOperLogDao() SysOperLogDao {
	return &sysOperLogDao{
		db: database.GetDB(),
	}
}

func (o *sysOperLogDao) Create(operLog *model.SysOperLog) error {
	logger.Info("创建操作日志")
	return o.db.Create(operLog).Error
}

func (o *sysOperLogDao) GetByID(id int64) (*model.SysOperLog, error) {
	logger.Debug("根据ID获取操作日志", zap.Int64("oper_id", id))
	var operLog model.SysOperLog
	err := o.db.Where("oper_id = ?", id).First(&operLog).Error
	return &operLog, err
}

func (o *sysOperLogDao) Delete(id int64) error {
	logger.Info("删除操作日志", zap.Int64("oper_id", id))
	return o.db.Where("oper_id = ?", id).Delete(&model.SysOperLog{}).Error
}

func (o *sysOperLogDao) List(page, pageSize int) ([]*model.SysOperLog, int64, error) {
	logger.Debug("获取操作日志列表", zap.Int("page", page), zap.Int("page_size", pageSize))
	var operLogs []*model.SysOperLog
	var total int64

	offset := (page - 1) * pageSize
	db := o.db.Model(&model.SysOperLog{})

	if err := db.Count(&total).Error; err != nil {
		return nil, 0, err
	}

	if err := db.Offset(offset).Limit(pageSize).Order("oper_time DESC").Find(&operLogs).Error; err != nil {
		return nil, 0, err
	}

	return operLogs, total, nil
}

func (o *sysOperLogDao) CleanAll() error {
	logger.Info("清空操作日志")
	return o.db.Session(&gorm.Session{AllowGlobalUpdate: true}).Delete(&model.SysOperLog{}).Error
}
